/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import Datos.Conexion;
import Datos.Global;
import Killer.jImputSimpleBox;
import Killer.jMessageFlush;
import Negocio.clsCategoria;
import Negocio.clsIngrediente;
import Negocio.clsInsumo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author RODRIGO
 */
public class frmAgregarIngrediente extends javax.swing.JDialog {

    // Conexion conn = new Conexion();
    DefaultTableModel dtmLista, dtmIngredientes, dtmModel;
    JTable table;
    private int cantFila, nroFilasAumentadas;

    public frmAgregarIngrediente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        this.setTitle("Agregar Ingredientes");
        dtmLista = (DefaultTableModel) jtbbuscarIngrediente.getModel();
        dtmIngredientes = (DefaultTableModel) tbListaIngredientes.getModel();
        this.cargarTablaBuscadorIngredientes();
        this.cargarTabla_listaIngrediente();

        table = new JTable();
        dtmModel = (DefaultTableModel) table.getModel();
        dtmModel.addColumn("idInsumo");
        dtmModel.addColumn("ingrediente");
        dtmModel.addColumn("cantidad");
        dtmModel.addColumn("unidad");
        dtmModel.addColumn("precio");
        dtmModel.addColumn("valor");


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        cbxCategorias = new javax.swing.JComboBox();
        lblLupita = new javax.swing.JLabel();
        txtBuscador = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbbuscarIngrediente = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        cbxSustituto = new javax.swing.JComboBox();
        btnAgregar = new javax.swing.JButton();
        btnQuitar = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        tbListaIngredientes = new javax.swing.JTable();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        setType(java.awt.Window.Type.UTILITY);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                cerrarVentana(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 204, 204));

        jPanel2.setBackground(new java.awt.Color(255, 255, 153));

        cbxCategorias.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        cbxCategorias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ver Todos" }));
        cbxCategorias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxCategoriasActionPerformed(evt);
            }
        });

        lblLupita.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/lupa.png"))); // NOI18N

        txtBuscador.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        txtBuscador.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscadorKeyReleased(evt);
            }
        });

        jtbbuscarIngrediente.setBackground(new java.awt.Color(255, 153, 153));
        jtbbuscarIngrediente.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jtbbuscarIngrediente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID Insumos", "Ingrediente", "Unidad", "Precio", "Valor Proteico", "cantidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtbbuscarIngrediente.setGridColor(new java.awt.Color(255, 204, 204));
        jtbbuscarIngrediente.setRowHeight(20);
        jtbbuscarIngrediente.setSelectionBackground(new java.awt.Color(255, 204, 204));
        jtbbuscarIngrediente.setSelectionForeground(new java.awt.Color(0, 0, 0));
        jtbbuscarIngrediente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbbuscarIngredienteMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbbuscarIngrediente);
        jtbbuscarIngrediente.getColumnModel().getColumn(0).setMinWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(0).setPreferredWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(0).setMaxWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(1).setPreferredWidth(180);
        jtbbuscarIngrediente.getColumnModel().getColumn(2).setMinWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(2).setPreferredWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(2).setMaxWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(3).setMinWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(3).setPreferredWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(3).setMaxWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(4).setMinWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(4).setPreferredWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(4).setMaxWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(5).setMinWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(5).setPreferredWidth(0);
        jtbbuscarIngrediente.getColumnModel().getColumn(5).setMaxWidth(0);

        jLabel1.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jLabel1.setText("Posibles sustitutos:");

        cbxSustituto.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbxCategorias, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(txtBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblLupita)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbxSustituto, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbxCategorias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblLupita))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbxSustituto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/next2.png"))); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/forward2.png"))); // NOI18N
        btnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarActionPerformed(evt);
            }
        });

        jScrollPane4.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N

        tbListaIngredientes.setBackground(new java.awt.Color(255, 153, 153));
        tbListaIngredientes.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        tbListaIngredientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id_insumo", "Ingrediente", "Cantidad", "Unidad", "Precio", "Valor Proteico"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbListaIngredientes.setToolTipText("");
        tbListaIngredientes.setGridColor(new java.awt.Color(255, 255, 255));
        tbListaIngredientes.setRowHeight(20);
        tbListaIngredientes.setSelectionBackground(new java.awt.Color(255, 204, 204));
        jScrollPane4.setViewportView(tbListaIngredientes);
        tbListaIngredientes.getColumnModel().getColumn(0).setMinWidth(0);
        tbListaIngredientes.getColumnModel().getColumn(0).setPreferredWidth(0);
        tbListaIngredientes.getColumnModel().getColumn(0).setMaxWidth(0);
        tbListaIngredientes.getColumnModel().getColumn(1).setPreferredWidth(120);
        tbListaIngredientes.getColumnModel().getColumn(2).setPreferredWidth(40);
        tbListaIngredientes.getColumnModel().getColumn(3).setPreferredWidth(50);
        tbListaIngredientes.getColumnModel().getColumn(4).setPreferredWidth(35);
        tbListaIngredientes.getColumnModel().getColumn(5).setPreferredWidth(40);

        btnAceptar.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/icon_accept.gif"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/action_stop.gif"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnAgregar)
                            .addComponent(btnQuitar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 610, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(164, 164, 164)
                        .addComponent(btnAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnQuitar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnAceptar))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbxCategoriasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxCategoriasActionPerformed
        if (clsCategoria.isHabilitado) {
            String nombCategoria = cbxCategorias.getSelectedItem().toString();
            String sql;
            if (nombCategoria.equals("Ver Todos")) {
                sql = "CALL `obtener_listaIngrediente`(" + 0 + "," + 0 + ")";
            } else {
                sql = "CALL `buscador_Ingrediente`(" + "''," + '"' + nombCategoria + '"' + "," + 3 + ")";
            }
            clsIngrediente.mostrarTablaIngrediente(jtbbuscarIngrediente, sql);
        }
        txtBuscador.setText("");
    }//GEN-LAST:event_cbxCategoriasActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed

        for (int i = 0; i < jtbbuscarIngrediente.getRowCount(); i++) {
            if (jtbbuscarIngrediente.isRowSelected(i)) {
                Object[] o = new Object[6];
                int idInsumo = (int) (jtbbuscarIngrediente.getValueAt(i, 0));
                String nombreIngrediente = (String) jtbbuscarIngrediente.getValueAt(i, 1);
                String unidad = (String) jtbbuscarIngrediente.getValueAt(i, 2);
                o[0] = idInsumo;
                o[1] = nombreIngrediente;

                if (!existeIdIngrediente(idInsumo) || tbListaIngredientes.getRowCount() == 0) {
                    jImputSimpleBox.showSimpleBox("Ingrese la Cantidad de " + nombreIngrediente + "(" + unidad + " )", "");
                    if (jImputSimpleBox.btnAceptar) {
                        float cantidad = Float.valueOf(jImputSimpleBox.txtCantidad);
                        float costo = costoVerdadero((float) jtbbuscarIngrediente.getValueAt(i, 4),//3 
                                                     (float) jtbbuscarIngrediente.getValueAt(i, 5), 
                                                      cantidad);  //calculo el costo real ,hace la regla de tres simple segun la cantidad ingresada del insumo agregado
                        float valorPro = valorProteicoTotal((float) jtbbuscarIngrediente.getValueAt(i, 3), 100, cantidad);  //4
                        o[2] = cantidad;
                        o[3] = unidad;
                        o[4] = costo;
                        o[5] = valorPro;
                        dtmIngredientes.addRow(o);
                        clsIngrediente.insertar_Ingrediente(idInsumo, frmReceta.IdRecetaSimple, cantidad);

                        nroFilasAumentadas++;

                        frmReceta.costoTotal += costo;    // suma el costo total de la receta
                        frmReceta.valorProteico += valorPro;   // suma el valor proteico de la receta
                    }
                } else {
                    jMessageFlush.showMessageFlush("Ya existe " + '"' + nombreIngrediente + '"' + " en la lista de ingrediente", jMessageFlush.shortTime, jMessageFlush.Warning);
                }
            }
        }
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void txtBuscadorKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscadorKeyReleased
        String NombreIngrediente = txtBuscador.getText();
        String nombCategoria = cbxCategorias.getSelectedItem().toString();
        String sql;
        if (nombCategoria.equals("Ver Todos")) {
            sql = "CALL`buscador_Ingrediente`(" + '"' + NombreIngrediente + '"' + ",''," + 2 + ")";
        } else {
            sql = "CALL`buscador_Ingrediente`(" + '"' + NombreIngrediente + '"' + "," + '"' + nombCategoria + '"' + "," + 1 + ")";
        }
        clsIngrediente.mostrarTablaIngrediente(jtbbuscarIngrediente, sql);
    }//GEN-LAST:event_txtBuscadorKeyReleased

    private void btnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarActionPerformed

        int f = 0;
        while (f < tbListaIngredientes.getRowCount()) {
            if (tbListaIngredientes.isRowSelected(f)) {
                frmReceta.costoTotal -= (float) tbListaIngredientes.getValueAt(f, 4);  //resta el costo total de la receta
                frmReceta.valorProteico -= (float) tbListaIngredientes.getValueAt(f, 5);  // resta el valor proteico de la receta

                dtmModel.addRow(obtener_filaEliminada(f));
                clsIngrediente.eliminar_ingredienteUnico((int) tbListaIngredientes.getValueAt(f, 0), frmReceta.IdRecetaSimple);

                dtmIngredientes.removeRow(f);
            } else {
                f++;
            }
        }
    }//GEN-LAST:event_btnQuitarActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        frmReceta.cbxIngrediente.removeAllItems();
        for (int f = 0; f < tbListaIngredientes.getRowCount(); f++) {
            frmReceta.cbxIngrediente.addItem(tbListaIngredientes.getValueAt(f, 1));
        }
        
        Global.costoTotalSimple = frmReceta.costoTotal;
        Global.valorTotalSimple = frmReceta.valorProteico;
        frmReceta.lblCostoReceta.setText(String.valueOf(frmReceta.costoTotal+Global.costoTotalComplem));
        frmReceta.lblValorProteico.setText(String.valueOf(frmReceta.valorProteico+Global.valorTotalComplem));
        this.dispose();
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        if (cantFila > tbListaIngredientes.getRowCount()) {
            // si disminuyeron filas
            this.aumentarFilasEliminadas();
        } else {
            // si aumentaron filas
            this.eliminarFilasAumentadas();
        }
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void cerrarVentana(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_cerrarVentana
        if (cantFila > tbListaIngredientes.getRowCount()) {
            // si disminuyeron filas
            this.aumentarFilasEliminadas();
        } else {
            // si aumentaron filas
            this.eliminarFilasAumentadas();
        }
    }//GEN-LAST:event_cerrarVentana

    private void jtbbuscarIngredienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbbuscarIngredienteMouseClicked
        int idIngrediente = (int) jtbbuscarIngrediente.getValueAt(jtbbuscarIngrediente.getSelectedRow(), 0);
        String sql = "CALL  `mostrar_Sustituto`(" + idIngrediente + ")";
        clsInsumo.cargarSustituto(cbxSustituto, sql);
    }//GEN-LAST:event_jtbbuscarIngredienteMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmAgregarIngrediente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmAgregarIngrediente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmAgregarIngrediente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmAgregarIngrediente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frmAgregarIngrediente dialog = new frmAgregarIngrediente(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnQuitar;
    private javax.swing.JComboBox cbxCategorias;
    private javax.swing.JComboBox cbxSustituto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jtbbuscarIngrediente;
    private javax.swing.JLabel lblLupita;
    private javax.swing.JTable tbListaIngredientes;
    private javax.swing.JTextField txtBuscador;
    // End of variables declaration//GEN-END:variables

    private void cargarTablaBuscadorIngredientes() {
        String sql = "CALL `obtener_listaIngrediente`(" + 0 + "," + 0 + ")";
        clsIngrediente.mostrarTablaIngrediente(jtbbuscarIngrediente, sql);

        sql = "CALL `obtener_listaCategorias`";
        clsCategoria.obtener_listaCategorias(cbxCategorias, sql);
    }

    private void cargarTabla_listaIngrediente() {
        Global.limpiarTabla(tbListaIngredientes);
        try {
            String sql = "CALL `obtener_listaIngrediente`(" + frmReceta.IdRecetaSimple + "," + 1 + ")";
            ResultSet rs = Conexion.executeQuery(Conexion.conn, sql, null);
            while (rs.next()) {
                Object[] o = new Object[6];
                o[0] = rs.getInt(1);
                o[1] = rs.getString(2);
                o[2] = rs.getFloat(3);
                o[3] = rs.getString(4);
                float costo = costoVerdadero(rs.getFloat(6), rs.getFloat(5), rs.getFloat(3)); //costo insumo,cantidad insumo, porcion a utilizar
                float valor = valorProteicoTotal(rs.getFloat(7), 100, rs.getFloat(3));
                o[4] = costo;
                o[5] = valor;

                frmReceta.costoTotal += costo;
                frmReceta.valorProteico += valor;

                dtmIngredientes.addRow(o);
            }
            cantFila = tbListaIngredientes.getRowCount();
            nroFilasAumentadas = 0;
        } catch (SQLException ex) {
            System.out.println("error al cargar tabla ingredientes " + ex);
        }

    }

    private boolean existeIdIngrediente(int idInsumoCargado) {
        List<Integer> L = new ArrayList<>();
        for (int i = 0; i < tbListaIngredientes.getRowCount(); i++) {
            L.add((Integer) tbListaIngredientes.getValueAt(i, 0));
        }
        return L.contains(idInsumoCargado);
    }

    private Object[] obtener_filaEliminada(int fila) {
        Object[] o = new Object[6];
        for (int c = 0; c < tbListaIngredientes.getColumnCount(); c++) {
            o[c] = tbListaIngredientes.getValueAt(fila, c);
        }
        return o;
    }

    private void eliminarFilasAumentadas() {
        int k = tbListaIngredientes.getRowCount();
        for (int f = 0; f < nroFilasAumentadas; f++) {
            clsIngrediente.eliminar_ingredienteUnico((int) tbListaIngredientes.getValueAt(k - 1, 0), frmReceta.IdRecetaSimple);
            frmReceta.costoTotal -= (float) tbListaIngredientes.getValueAt(k - 1, 4);
            frmReceta.valorProteico -= (float) tbListaIngredientes.getValueAt(k - 1, 5);
            dtmIngredientes.removeRow(k - 1);
            k--;
        }
        nroFilasAumentadas = 0;
    }

    private void aumentarFilasEliminadas() {
        for (int i = 0; i < table.getRowCount(); i++) {
            Object[] o = new Object[6];
            o[0] = table.getValueAt(i, 0);
            o[1] = table.getValueAt(i, 1);
            o[2] = table.getValueAt(i, 2);
            o[3] = table.getValueAt(i, 3);
            o[4] = table.getValueAt(i, 4);
            o[5] = table.getValueAt(i, 5);
            dtmLista.addRow(o);
            clsIngrediente.insertar_Ingrediente((int) table.getValueAt(i, 0),
                    frmReceta.IdRecetaSimple,
                    (float) table.getValueAt(i, 2));
            frmReceta.costoTotal += (float) table.getValueAt(i, 4);
            frmReceta.valorProteico += (float) table.getValueAt(i, 5);
        }
        Global.limpiarTabla(table);
    }

    public static  float costoVerdadero(float costoInsumo, float cantidadInsumo, float cantidadPorcion) {
        return (cantidadPorcion * costoInsumo) / cantidadInsumo;
    }

    public static  float valorProteicoTotal(float valorProteicoInsumo, float valorInsumo, float cantidad) {
        return (cantidad * valorProteicoInsumo) / valorInsumo;
    }
}
